Repository navigation
Conversation
NXstress's detector chain did not place pixels as reduction does: entered at the innermost transformation (NeXus) it applied 2theta_0 first and the shifts last, about X, with no arm angle. Nothing in PyRS read it (reduction unaffected); external NeXus tools were misled. Design approved on #1099. - calibration_nexus.detector_transformations: the calibration file's chain writer, now shared; NXstress writes shift_x ... two_theta_0 (about Y), arm_rotation, each calibration parameter with <name>_errors. - arm_rotation per scan point, -(2theta log), growable on append; NaN without a 2theta log. - One arm_length: the runs' L2 log when present (what reduction uses), else the instrument's; an L2 that differs between scan points is refused. - Errors from the applied calibration, -1 where unknown. - A workspace loaded from a project file keeps the calibration reduction applied (get_recorded_calibration, from the file's record), so NXstress from reduced data now writes the calibrated detector instead of the nominal one. Kept apart from get_detector_shift: reduction applies that when no calibration file is given. - instrumentFromNexus reads the new names first, then the old ones. - Tests: the chain applied without DetectorModel reproduces lab_positions at every scan point; recorded calibration and errors; unknown errors -1; differing L2 refused; missing arm angle NaN; old layout read; workspace loading keeps the record apart. Recorded in ground_truths. Refs #1099, #1054 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… calibration - Reading NXstress back dropped the calibration's <name>_errors, so writing it again (e.g. after refitting peaks) wrote -1 for every parameter. instrumentFromNexus's companion shiftErrorFromNexus reads them, the read-back workspace keeps them (set_recorded_calibration), and the writer uses them when the recorded calibration is the workspace's shift. - A workspace built from several project files (append_hidra_project) kept the first file's recorded calibration, so NXstress labelled every scan point with it. The appended file's record must match, or the combined data records none (with a terminal warning). Refs #1099 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ies, DD-30 - T1: real-data test (HB2B_3510 reduced with the ring reference calibration) that the NXstress chain carries the applied calibration, its errors, arm angle and arm length, and places the real pixels where lab_positions does. - T2-T7, T10: per-parameter errors, unknown errors, own shift vs another record, L2 refusal, missing arm angle, old layout read-back, AAA structure. - T3: appended arm angles, appending to a pre-#1099 entry, differing L2 refused. - T8: arm angle and arm length checked on the real sample-position fixture. - T9: a record of no calibration, and an unreadable record (warned, data still load). - C1: refusing an append to a pre-#1099 entry now says why. - DD-30: reduction to a new file writes no instrument geometry (deferred). Refs #1099, #1054 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars.
|
…-chain # Conflicts: # docs/deferred_defects.md
ekapadi
left a comment
There was a problem hiding this comment.
PR review — #1132 (feature/1099-nxstress-chain)
This is the review of PR #1132: next..feature/1099-nxstress-chain, based on next
at 9fd090e2. With it, NXstress writes the calibration file's detector chain, including the per-scan-point
arm angle and the calibration's errors.
#1132 overlaps the planned NXstress implementation work that connects the NXstress backend to PyRS core. Its
parts are named here by number and slug. Two matter most:
- the phase-3 PR (
EWM17019_NXstress_hookup_phase_3): the 05 strain-stress-viewer subspec for the NXstress
hookup, with the same base as #1132; - the 04d extended-two-theta subspec for the NXstress hookup (diffractogram identity, eta wedges and
two-theta axes), which follows phase 3.
This review first settles how #1132 fits with both. The reviewer's specific questions, and then a general
review, follow below.
Summary notes:
-
The conflicts with my 'phase-3' PR are quite minor, so we don't need to be too concerned with that!
-
Several of the review comments below were triggered by rules in my own
CLAUDE.local.md, which is fairly complex.
There are several of these rules that I'm recommending we promote into the repository'sCLAUDE.md.
Recommended coding rules to move to CLAUDE.md
Several findings below rest on rules that are, today, only in the reviewer's private CLAUDE.local.md, plus
one new rule this review proposes. #1132's author does not have that file, so the PR cannot be held to them
as written. The reviewer intends to move them into CLAUDE.md, so that they become project rules (CLAUDE.md
names .github/copilot-instructions.md as its mirror, but that file does not exist yet); that decision is
not yet approved. Until it is, findings that rest on these rules are recommendations to #1132's author, not
requirements, and each one points back here with "(see Recommended coding rules, above)".
Each rule below lists the findings it drives, then the exact text to add to CLAUDE.md, ready to paste.
The first four are copied verbatim from CLAUDE.local.md; the fifth is new. They would sit together after
CLAUDE.md's Code Quality Standards, as top-level ## sections, as they do in CLAUDE.local.md.
1. None must name a value, not a gap
This is a general rule, which has evolved over time. It was primarily triggered by the observation that
many developers reflexively set the default values of parameters to None, and then this default value
serves as a sentinal conflating both cases: (i) the parameter is unset, and (ii) the parameter has its default value.
In most cases, an unset parameter should trigger an error, and under this common usage, this case can no longer be detected!
- R2, G1:
Noneas the applied calibration means the nominal detector, and nothing else; the full policy
is in R2, under TheNonepolicy. - R2, G2: an unknown calibration, including one merged from different calibrations, gets its own literal
value (CalibrationSource.UNKNOWN, rule 5), notNone. - G7: the
shift_error=Nonedefault onset_recorded_calibration(one filler, so no default). - Related: phase 3 adds
pyrs.utilities.unset.Unsetfor "not supplied"; it is not onnextyet.
## `None` must name a value, not a gap
**Absence must be distinguishable from a falsey value.** `""`, `[]`, `0` and
`None` each mean something real somewhere, so none of them can also mean "not
supplied". `arg: Optional[T] = None` is where that collapse usually enters: the
default makes "the caller decided `None`" and "the caller passed nothing" the same
observation, and nothing at the call site recovers the difference. An argument
whose absence would be a wiring bug therefore carries **no default at all** —
required and keyword-only. `None` is then free to mean what it says.
Two corollaries:
- `None` must name a value in the argument's **domain**, never a gap. A `None`
standing in for "not computed yet" makes a half-built object indistinguishable
from a finished one; whatever the consumer actually wanted — usually an empty
collection — was the right value all along.
- **Count the fillers.** One filler means absence is a bug, so no default. When
two parties fill a field — a model plus a prep hook, or a writer plus a reader
deserialising stored rows — absence from *one* of them is the normal case, so
the default is correct and the guard moves to whichever filler can tell that it
failed. (A row written by an *older version* of the code is not a filler: that is
a migration, done with the change, not an ongoing absence to guard against.)
For example:
```python
class ReductionRequest(BaseModel):
calibration_file: Optional[str] = None # the caller never supplies this; a later step fills it
def prepare(request: ReductionRequest) -> None:
...
raise RuntimeError("calibration_file could not be resolved") # never a quiet return
```
Why: requiring a field that a *second* party fills publishes it to the first one, which
may have no way to supply it correctly. And a guard needs the information to be right: a
step that sees only the payload cannot tell "this field does not exist here" from "this
field was lost", so that check belongs in a test that reads the schema instead.2. Keyword-only arguments
This rule was triggered by the observation that in larger codebases, as the functionality is extended,
many API functions gradually accumulate more and more parameters. Many silent defects are caused
by mis-ordering positional parameters. Use of proper type annotation can help with this issue, but
in reality, it's somewhat in conflict with Python's design [and strength] as a programming language.
Under an object-oriented programming paradigm, we [at least attempt to] use object scope to limit the size of these parameter sets, but
this cannot always be done successfully. A work-around, which fixes many silent defects, is to simply specify
all parameters using their names in production code. This rule applies this approach, strictly limiting the number of
positional parameters, and then assigning keyword names to the bulk of the rest of the parameters.
- G7:
detector_transformations(shifts, shifts_error, arm_length, arm_rotation=None), called by position.
## Keyword-only arguments
Any function or method with more than 3 arguments, or with any argument
that has a default value, keeps only its first one or two "primary
subject" arguments positional — every other argument, whether it has a
default or is required, goes after a bare `*`. This applies even to
required arguments once the threshold is crossed, so that a function's
argument list can grow later without breaking a positional call site.
```python
def reduce_sub_run(
run_number: int,
*,
detector_name: str,
calibration_file: str,
sub_runs: list[int],
output_path: str,
): ...
```
Why: adopted as a general convention rather than from a specific PyRS incident — no
function here has yet crossed the 3-arg/any-default threshold with a positional
signature, so there is no local call-site cost to cite either way. Keeping required
arguments positional past that threshold is what causes silent breakage later — a
caller relying on positional order has no warning when a new required argument is
inserted in the middle. Apply this when writing or extending a function that crosses
the threshold, not as a retroactive sweep of existing ones.3. Import placement
- G7: unjustified function-local imports in two tests and the
_calibrated_instrumenthelper.
## Import placement
**All imports go at the top of the file.** A function-local (deferred)
import is allowed only when a top-level import would actually break — and
when it is, the reason goes in a comment on the import line or immediately
above it, naming the specific cycle or condition:
```python
def get_handle(self, name: str):
from other_module import Handle # deferred: other_module imports this module
...
```
The three cases that genuinely justify deferring, and nothing else:
1. **A real circular import.** Name the other module and the direction, as
above. "Might be circular" is not a justification — if you have not seen
the `ImportError`, move it to the top.
2. **An optional dependency** not installed in every environment
(`nltk`, `sounddevice`, ...). Say which environment lacks it.
3. **A genuinely expensive module-load** deferred off a hot import path, with
a note on what it costs.
Do **not** defer an import to make `unittest.mock.patch` work. `from x import
f` at module level binds `f` at import time, so patching `x.f` does not reach
it — but the fix is to import the *module* at the top and call through it,
which stays patchable:
```python
import some_module # top-level
def get_resource():
return some_module.get_settings().resource_root
```
Why: a deferred import hides a module's real dependency graph, moves
`ImportError`s from startup to whenever that branch first runs, and costs a
`sys.modules` lookup on every call. PyRS already has instances of the shape this
rule targets — `pyrs/utilities/NXstress/_peaks.py`'s `from ._fit import
_PeakParameters, _BackgroundParameters` and `from ._definitions import
GROUP_NAME, UNDEFINED_PEAK_TAG`, both inside a method body with no comment
justifying the deferral. This rule applies to code you touch; existing
instances are not to be swept up unless asked.4. Private names do not cross module boundaries
- G7:
test_nxstress_calibration.pyimports_chain_matrixfromtest_instrument.py. The test exception
covers a test importing a private from the module it tests, not from another test module.
## Private names do not cross module boundaries
A leading underscore means *this module owns this name*. Another module
importing it is a contradiction in terms, and it is always a signal about
placement rather than a shortcut worth taking:
```python
from some_package.internals import PublicThing, _private_helper # do NOT do this
```
Two sanctioned fixes, and which one applies is a question about ownership:
1. **The name is genuinely part of that module's contract** and was
underscore-prefixed by habit. Drop the underscore, so the module exports it
deliberately.
2. **Two modules both need it and neither owns it.** Extract it to a leaf
module they both import. This is the case whenever the import also closes an
import cycle — the cycle is the evidence that the name is in the wrong place.
Two things this does **not** forbid:
- `import public_name as _alias`, which is the opposite move: taking a public
name and keeping it out of the importing module's own surface. The rule is
about the name at its *definition*, not at the call site.
- A **test** importing a private from the module it is testing —
`tests/unit/pyrs/utilities/NXstress/test_peaks_read.py` reaching directly for
`_peaks._Peaks` and `_fit._PeakParameters`. That is ordinary white-box
testing, and the test breaking on a rename is the intended behaviour rather
than collateral damage.
- A package's own orchestrating module assembling its public surface from its
sibling private modules — `pyrs/utilities/NXstress/NXstress.py` importing
`_Instrument`/`_Sample`/`_Fit`/`_Peaks` from `_instrument.py`/`_sample.py`/
`_fit.py`/`_peaks.py`. These are the package's own internals talking to each
other, not one package reaching into another's; see *Private modules are not
the same thing as private names* below.
Why: a private name carries no stability contract, so renaming one inside its
owning module is an unannounced breaking change to code its author never looked
at — and the underscore is precisely what told that author they were free to
rename it. This rule applies to code you touch; existing violations are not to
be swept up unless asked.
### Private modules are not the same thing as private names
`pyrs/utilities/NXstress/` is built from underscore-prefixed *files* —
`_peaks.py`, `_fit.py`, `_definitions.py`, `_sample.py`, `_instrument.py`,
`_discriminator.py`, `_input_data.py`, `_runs.py`, `_workspace_key.py`,
`_validation.py`, `_append.py`, `_read.py` — each an implementation detail of the
`NXstress` package as a whole, not of any one file inside it. That is a
**layout** choice, answered by *where a file sits*, and this rule does not
touch it: `NXstress.py` importing `_Peaks` from `_peaks.py` is the package
assembling its own public surface, the same as the test exception above.
The rule is violated when a module **outside** `pyrs/utilities/NXstress/`
imports one of these names directly — `pyrs.core` reaching for
`pyrs.utilities.NXstress._peaks._Peaks` instead of whatever `NXstress`
re-exports publicly. The leading underscore on a *module* still means
something; it just answers a narrower question — "is this file part of the
package's own internals" — than the leading underscore on a *name* crossing a
boundary the package did not draw.5. Named states are literals, not free text
- R2: the calibration's source becomes
CalibrationSource, and a merge recordsCalibrationSource.UNKNOWN. - G2, G3, G9: every "calibration unknown" case uses that one member, and NXstress writes it as its marker.
- G7: the
AppliedCalibrationrecord carries aCalibrationSource.
## Named states are literals, not free text
**A value that names one of a fixed set of states is defined once, as a str-valued
`Enum` (or a `Literal` type), and every module that writes, reads or compares it
imports that one definition.** A state spelled out as a bare string at each use
(`"none"`, `"file"`, `"unknown"`, ...) lets a typo silently become a new state that
no reader handles, and leaves no single place that lists the states there are.
```python
class CalibrationSource(str, Enum):
NONE = "none" # nominal detector: no calibration applied
FILE = "file" # a calibration file
WORKSPACE = "workspace" # the workspace's own shift
UNKNOWN = "unknown" # a calibration was applied, but which one cannot be stated
```
- **Keep the stored strings as the members' values**, so files already written read
back unchanged and no migration is needed.
- **A stored string that is not a member is read as an explicit fallback member**
(usually `UNKNOWN`), with a warning: never passed through as a new state, and
never turned into `None`.
- This pairs with *`None` must name a value, not a gap*: "unknown", "mixed" or
"lost" are states of their own and get members of their own, rather than
borrowing `None`.
Why: the review of PR #1132 found the calibration's source written as free text in
several modules: `"none"`/`"file"`/`"workspace"` in `HidraSetup`, `"unknown"` in the
project-file writer, and `record.get("source", "none")` defaults in the readers.
Nothing ties these together, so a misspelling in any one of them is a new,
unhandled state rather than an error. This rule applies to code you touch; existing
instances are not to be swept up unless asked.The review practice also follows one CLAUDE.local.md rule that is about process, not code: probe before
asserting (Auditing a Plan or Subspec). A claim about how another module treats our output is backed by a
probe: a short script driving the real code, run before the claim is made. R3's check of the detector
shift is one. It is part of a more comprehensive plan-audit
process as a whole, so it is not proposed for CLAUDE.md here.
R1 — Merge order: #1132 may merge before phase 3 (decision)
Concern: #1132's NXstress changes might clash with phase 3's combined (run_number, scan_point)
index, or with the planned 04d work. If so, they would have to wait for both PRs.
Resolution: they do not clash. #1132 may merge first, and phase 3 is then rebased onto it. This is
the order we propose.
Evidence:
-
A trial merge touches no worktree or ref:
git merge-tree --write-tree --name-only origin/EWM17019_NXstress_hookup_phase_3 upstream/feature/1099-nxstress-chain.
It conflicts in four files only:docs/deferred_defects.mdanddocs/ground_truths.md: the conflict is only where both sides add at the
end. The DD numbers are distinct: phase 3 adds DD-6 to DD-9 and DD-32, #1132 adds DD-34.tests/unit/pyrs/utilities/NXstress/test_append.py: both sides add classes at the end (phase 3:
TestRunIndexOnAppend,TestAFailureWhileComputingWritesNothing; #1132:TestDetectorChainOnAppend).pyrs/utilities/NXstress/NXstress.py: #1132 adds two lines to the old reader's_workspaceFromNexus,
which phase 3 replaced with_read.py.
_instrument.py,workspaces.pyandtest_workspaces.pymerge without conflict. -
The
(run, scan_point)index is unaffected. The one new per-scan-point dataset is
DETECTOR/transformations/arm_rotation(_Instrument._concatenated_arm_rotation).- It is built positionally, in workspace order over
ws.get_sub_runs(). Phase 3 builds every other
column in the scan-point family the same way:monochromator/wavelength,SAMPLE_DESCRIPTION/scan_point
andrun_number. So its rows line up with the index with no further work. - It is created with
growable(1), grows throughtail_append, and is listed in
_Instrument.appendableDatasets. So phase 3's compute-then-write append (deferred_appends) and its
shape check (_append.validate_appendable_shapes) cover it unchanged. - The reader never slices it by
rows: the arm angle comes back through the2thetasample log. So
phase 3's split of an entry into its workspaces is unaffected.
- It is built positionally, in workspace order over
-
04d works in
FIT/peaks, on the two-theta axes and in the reduction call. It does not touch the
detector chain; in the instrument group it changes only the mask-name encoding underinstrument/masks.
It sharesworkspaces.pyand_instrument.py(and the teststest_workspaces.pyandtest_append.py)
with #1132, in different code.
R2 — One NXstress entry holds one calibration (working answer)
Question: should an NXstress entry be able to combine runs reduced with different calibrations? Phase
3 writes several runs into one entry; the strain/stress viewer's three directions are the ordinary case.
With #1132, _Instrument._entry_wide_geometry refuses runs whose applied calibrations or L2 differ
(_applied_shift, _effective_geometry).
Working answer: keep the refusal. Settle which calibration to use before saving as NXstress.
A mixed entry is technically feasible, for example by storing the calibration per scan point, behind a
Config flag. We decline it: that much flexibility mostly lets users make mistakes.
Merging in PyRS core is accepted, and records the calibration as unknown.
HidraWorkspace.append_hidra_project(CombineRuns, and the peak-fitting multi-file load) merges runs
whose recorded calibrations differ, and warns. That stays: the rule's scope is that the NXstress backend
never merges calibrations; a merge in PyRS core is the user's explicit choice.- What changes is the value the merge records. Today it sets the record to
None. It should record the
calibration as unknown, using the literalCalibrationSource.UNKNOWNbelow, with the reason ("merged
from runs reduced with different calibrations"). NXstress then writes the "calibration unknown" marker (G2),
not the nominal chain.
The None policy for the applied calibration (the None rule; see Recommended coding rules, above).
None names exactly one value in the calibration's domain: the nominal detector — reduction applied no
calibration. It never stands for "not known", "lost" or "mixed". Each of those is a fact about the data
that the record must keep, so each gets its own explicit value.
Why this is better than None for a merge:
Noneis a claim, not a gap. NXstress turnsNoneintocalibrated=Falseand the nominal chain: a
statement that the data were reduced with the uncalibrated detector. After a merge of calibrated runs
that statement is false, and nothing in the file says so.- It stays distinguishable. With
Nonefor both, a merged workspace and one that was never calibrated
look the same, as this section originally accepted. With an explicit value they do not, at no cost. - It reuses one state instead of adding cases. G2 already needs "unknown" for a record the file says
could not be written, or that could not be read. A merge is the same situation (a calibration was applied,
and which one cannot be stated), so the merge, G2's cases, G3's differing-errors merge and G9's missing
calibration field all land in one state, which NXstress writes one way.
Literal, not free text. Today the calibration's source is free-form text spread over several modules:
"none", "file", "workspace" in HidraSetup, "unknown" in the project-file writer
(file_object.py), and record.get("source", "none") defaults in the readers. A typo in any of them
silently becomes a new state. The suggestion is one str-valued enum, defined once and imported by every
module that writes or reads the record (HidraSetup, HidraProjectFile, HidraWorkspace, NXstress):
class CalibrationSource(str, Enum):
NONE = "none" # nominal detector: no calibration applied
FILE = "file" # a calibration file
WORKSPACE = "workspace" # the workspace's own shift
UNKNOWN = "unknown" # a calibration was applied, but which one cannot be stated- The stored strings are the ones already written, so existing project files read back unchanged.
- An unrecognised string in a file is itself read as
UNKNOWN, with a warning, never as a new state. - In memory, the record (G7's
AppliedCalibration) carries aCalibrationSource, and NXstress writes the
same literal as its marker, so both file formats use one vocabulary. CalibrationSource.NONEexists only as the stored string. A record stored with source"none"reads back as
theNonerecord, and anAppliedCalibrationnever carriesNONE, so "nominal detector" has exactly one
in-memory form.
Project files with no record at all are UNKNOWN too (recommended). Since #1053 every reduction
writes a record, with source "none" when no calibration was applied. A file with no record was therefore
reduced before #1053, with a calibration that cannot be known. Today it loads as None, and NXstress writes it
as uncalibrated (_load_recorded_calibration: "A file with no record (reduced before #1053, or never
calibrated) keeps None"). That is the same false claim as point 1 above. We recommend that such a file load as
CalibrationSource.UNKNOWN, with the reason "no calibration record (reduced before #1053)". The visible effect
is that NXstress writes the "calibration unknown" marker instead of calibrated=False for every pre-#1053
project file. That is the honest statement about those files, and it needs no migration: the file is not
changed, only what is said about it.
R3 — Can a detector shift be applied to the arm more than once?
Question (reviewer): in earlier PyRS it was possible to apply several calibrations to the arm by
accident, because nothing recorded whether a detector shift had already been applied. Does #1132 fix this?
Resolution: in practice, yes. Reduction could already apply a shift only once, through #1011 and #1053.
#1132 fixes the NXstress side and adds a record of the calibration that was applied. The root cause is
still in the code, though: the geometry still keeps no record of being calibrated, and the in-place shift
method is still there. We suggest #1132 record it as DD-35 (text below).
- Reduction (before #1132):
- Reduction builds the pixel positions afresh from the uncalibrated geometry every time
(ResidualStressInstrument.build_instrument→DetectorModel.lab_positions). It never writes the shift
back into the geometry. - A calibration file replaces the workspace's shift; the two are never added (
ReductionApp
passes the file'sDENEXDetectorShiftitself toreduce_diffraction_data).
- Reduction builds the pixel positions afresh from the uncalibrated geometry every time
- #1132:
- The old NXstress writer wrote
distance = geom.arm_length, with a TODO saying it could not tell whether
the shift had already been folded in. #1132 writes the arm length from the uncalibrated geometry or the
L2log, and writesshift_zas a step of its own in the chain. HidraWorkspacenow separates the shift a future reduction will apply (get_detector_shift) from the
one that was applied (get_recorded_calibration, from the project file's reduction record). NXstress
writes the recorded one only when the workspace has no shift of its own; otherwise it writes the shift
(G1).- The NXstress reader sets both. Reducing a read-back workspace again re-applies the same shift to the
uncalibrated positions; it does not stack a second one on top.
- The old NXstress writer wrote
- Still in the code (the suggested DD-35; it predates #1132, and no fix is asked of it):
DENEXDetectorGeometry.__init__takescalibratedand discards it. #1132's new_effective_geometry
passesFalse, and the NXstress reader (already before #1132) passes the file's flag; both values are
thrown away.DENEXDetectorGeometry.apply_shiftaddsshift_zto the arm length in place. It is reached only
throughHidraSetup.get_instrument_geometry(True), which nothing calls. It also raisesAttributeError
before changing anything.- Suggested fix: store the flag, and make
apply_shiftrefuse an already-calibrated geometry (or remove
the in-place path).
We probed this on feature/1099-nxstress-chain, driving PyRS's real code. It showed that:
- building the instrument twice with the same shift gives identical pixel positions, and leaves the
geometry's arm length unchanged (2.0 m before and after); - after a calibration file is loaded, the shift reduction will apply is the file's (
shift_z= −0.0201), not
the workspace's (0.03): the file's replaces it; - two NXstress write → read round trips keep the arm length (2.0) and
shift_z(0.03) apart and unchanged; HidraSetup.get_instrument_geometry(True)raisesAttributeError(DENEXDetectorShifthas no attribute
calibration_file) on every call, and the arm length stays 2.0;- a
DENEXDetectorGeometrybuilt withcalibrated=Truekeeps no attribute holding the flag.
Check 2 is at the HidraSetup.load_calibration_file level, as ReductionApp uses it. It is not
a full reduction.
Suggestion for #1132: add DD-35 to docs/deferred_defects.md. The defect is not caused by this PR. It
is related to it, though: #1132 adds a new place that passes the discarded calibrated flag
(_Instrument._effective_geometry; the reader, instrumentFromNexus, already did), and it removes the
NXstress TODO that pointed at the same gap. Recording it in this PR keeps that trail. The number 35 is free on next,
on #1132 and on phase 3. Suggested text:
- **DD-35**, 2026-11-21: `DENEXDetectorGeometry` takes a `calibrated` flag and discards it. Nothing then
records whether a detector shift has been applied to a geometry, and the one method that shifts a geometry in
place is broken.
- **Cause:** `DENEXDetectorGeometry.__init__` (`pyrs/core/instrument_geometry.py`) checks `calibrated` and
never stores it. `DENEXDetectorGeometry.apply_shift` adds `shift_z` to `_arm_length` in place, so a second
call would shift the arm again. It is reached only through `HidraSetup.get_instrument_geometry(True)`,
whose TODO lists the same three problems: it returns None, it could apply the shift repeatedly, and it
changes the uncalibrated geometry.
- **Today:** nothing calls `get_instrument_geometry(True)`. Reduction applies the shift to freshly computed
pixel positions (`DetectorModel.lab_positions`) and never changes the geometry. `apply_shift` raises
`AttributeError` before it changes anything: it reads `DENEXDetectorShift.calibration_file` from the class,
which has no such attribute. Every caller of the constructor, including NXstress, passes a flag that is
then thrown away.
- **Fix:** store the flag and expose it. Have `apply_shift` refuse a geometry that is already calibrated,
and either return the shifted geometry or remove `apply_shift` and `get_instrument_geometry(True)`
entirely.
**Found during:** the review of #1132 (#1099).
**Why it is deferred.** It predates #1099 and is in instrument geometry, which is scientific production code.R4 — General review
Six review agents read git diff 9fd090e2...19dd2525, with R1–R3 excluded, each for one aspect: code, tests,
comments, error handling, type design and simplification. Every finding was checked against the code before
being kept. Where several agents found the same thing, it is listed once below, as G1–G9; a finding with two
parts is cited under both.
What was checked and found sound:
pixi run mypy pyrs scripts tests→Success: no issues found in 282 source files.- The touched unit tests:
120 passed, 2 xfailed. - No agent found a logic error in the scientific behaviour:
- the chain's order and axes match
DetectorModel.lab_positions, i.e. reduction (whether reduction itself
is right is R5); arm_rotation= −(2theta log);- L2 matches what reduction uses;
- no correction parameter is added.
- the chain's order and axes match
G1 — The applied calibration: where it is held, how it is identified, and who records it — valid, important
Comment (agents): ReductionApp.reduce_data never sets _recorded_calibration. A workspace reduced in
the session therefore has no record, or keeps a stale one from its project file. And _Instrument._applied_shift
prefers get_detector_shift() (the shift the next reduction will apply) over the record, so a shift set by
FitCalibration but not yet used to reduce would be written as applied.
Reviewer: these are three separate issues, and the third is the point of G1.
- The calibration is held in more than one place, and they can disagree.
- A calibration has no identity. It should probably be identified by a hash key, and that key stored.
- Reduction does not record the calibration it applies. Applying a calibration is what reduction is
for, so it makes no sense that reduction is not the party that sets this one field.
Resolution: valid, all three. Latent today: no viewer that saves NXstress reduces data in the session
(they load project or NXstress files). It will bite the 07
manual-reduction-nxstress subspec for the NXstress hookup, where Manual Reduction writes NXstress from a
workspace reduced in the session.
1. Several holders. Calibration state is held in three places, none derived from the others:
| Holder | Holds | Set by |
|---|---|---|
HidraWorkspace._instrument_geometry_shift (get_detector_shift) |
the shift the next reduction will use | callers, FitCalibration, NXstress read-back |
HidraWorkspace._recorded_calibration |
(shift, shift_error) said to be applied |
project-file load/append (_read_recorded_calibration), NXstress read-back (set_recorded_calibration) |
ReductionApp._instrument (HidraSetup.calibration_record()) |
the full record: values, errors, file, calibration_file_sha256, source, provenance |
load_calibration_file or use_workspace_calibration, in reduce_data |
_applied_shift reconciles the first two by guessing: shift first, and the record's errors only if the record has
the same values. The third, the only complete one, goes to the project file at
save_diffraction_data → write_reduction_provenance and never reaches the workspace.
2. No identity. Two calibrations are "the same" if their seven shift values are equal, and this rule is coded
twice: workspaces._shift_values (for append_hidra_project) and _Instrument._shift_key (for the NXstress
refusal). Neither includes the wavelength, which the calibration also sets. A calibration_file_sha256 exists,
but it is a hash of the file, it is kept only in the project file's record, and _read_recorded_calibration
drops it when loading: the workspace keeps only (shift, shift_error). A calibration from FitCalibration in
the session has no file and so no hash at all.
3. Reduction does not record what it applies. reduce_data applies the calibration and save_diffraction_data
writes its full record to the project file, but neither sets it on the workspace. So the only way a workspace
learns what was applied to its own data is by being saved and loaded again.
Suggested Fix:
- One field, set by one party. The workspace holds a single record of the applied calibration. Reduction
sets it, every time, to what it applied (Nonefor the nominal detector). Loading a project file or reading
NXstress back restores it.get_detector_shift()stays as the request for the next reduction and is never
read as "applied";_applied_shift's fallback goes.- This builds on the author's own reasoning, not against it. #1132's ground truth ("NXstress detector chain
is the calibration file's") keeps the record apart fromget_detector_shift()on purpose: setting the
shift on load would make reducing a project file again, without a calibration file, silently switch from
the nominal geometry to the recorded one. The suggestion keeps that separation, and adds only that
reduction, not just loading, sets the record.
- This builds on the author's own reasoning, not against it. #1132's ground truth ("NXstress detector chain
- Identify a calibration by a hash key computed from its content: the canonical calibration values
(shift, 2θ₀, wavelength) and their errors. The same calibration then has the same key whether it came from
a JSON file, a NeXus file orFitCalibrationin the session. The file's sha256 stays as provenance. The key is
stored with the record in the project file and in NXstress, and_shift_values/_shift_keybecome one key
comparison. How a record whose errors are lost is keyed depends on G3's open question. - These change production behaviour, so the timing is the PR author's call: in #1132, or as a tracked
follow-up that must land before that 07 work.
Rebutted part: one agent's claim that "a read-back workspace that is reduced again applies the
calibration a second time" is wrong. The shift is re-applied to the nominal positions, not stacked, as R3's
probe showed.
Evidence:
grep -rn "_recorded_calibration\s*=\|set_recorded_calibration" pyrs→workspaces.py(init, load, append)
andNXstress.py(read-back) only; nothing inpowder_pattern.py.powder_pattern.py:save_diffraction_datacallsout_file.write_reduction_provenance(instrument=self._instrument, ...);
reduce_datawrites nothing back to the workspace except the wavelength.instrument_geometry.py:HidraSetup.calibration_record()includescalibration_file_sha256, set from
_file_sha256(calibration_file)inload_calibration_file.workspaces.py:_read_recorded_calibrationreturnsinstrument.geometry_shift, instrument.geometry_shift_error
only.
G2 — An unknown record is written as "uncalibrated" — valid, important
Comment (agent): _read_recorded_calibration returns None, the same value as "never calibrated", in three
cases:
- (a) the project file says the record could not be written:
{"source": "unknown", "error": ...}, from
file_object.py. The record has nocalibrationkey, so the reader returnsNone. This is silent. - (b) a source other than "none" with no
calibrationkey. This is silent. - (c) any exception, including programming errors, caught by
except Exceptionand logged as a warning.
NXstress then writes the nominal chain with calibrated=False. "Unknown" becomes a positive claim that no
calibration was applied.
Reviewer: "unknown calibration" is probably a state we should support. This is the None rule (see
Recommended coding rules, above): None is a value in the calibration's domain, the nominal detector, so
it cannot also mean "we do not know". An unknown calibration is set to its own, explicit value rather than
passed as None.
Resolution: valid. It is the same state R2 gives a merge of different calibrations: a calibration was
applied and cannot be stated. Here the file even says the record is unknown, and the reader throws that away.
Suggested Fix:
- Support "unknown" as a state of the applied-calibration record (G1's single field), distinct from
None
(nominal) and from any record with a content key: a record whose source is the literal
CalibrationSource.UNKNOWN(R2), carrying the recorded reason (the record'serrortext) and no content key. The project file already writes
that string.- It is not
Unset(phase 3, "the caller did not supply this"): the record was supplied, and says
the calibration is unknown.
- It is not
- NXstress writes it with a "calibration unknown" marker, not as the nominal chain.
- Every case records "unknown", and the file still loads. A failure to read the record is never a
refused load (refusing shuts down GUI options); it is a warning, and the record is marked unknown so that
NXstress writes the marker, not the nominal chain:-
(a) and (b): warn, naming the file and the recorded error, and record "unknown".
-
(c): split the single
except Exceptioninto separate blocks, so that the log tells a damaged or
unexpected file apart from a bug in PyRS:- the errors the record readers raise for a bad file:
OSError(HDF5 read),KeyError(missing
dataset or key),ValueError(includingjson.JSONDecodeError, andcalibration_from_dict's refusal
of a missingLambda),RuntimeError(read_reduction_instrument: no geometry stored;
calibration_from_dict: missingStatus) → a warning that the file's calibration record could not be
read; - any other
Exception→ logged as an error, with the traceback (logger.exception), saying it is
probably a PyRS bug and should be reported.
Both record "unknown" and let the load continue. The split is best-effort: a bug can also raise
KeyErrororValueError, so the "bad file" warning keeps the exception type and message as today. - the errors the record readers raise for a bad file:
-
Current behaviour, for reference: in all three cases the project file loads normally (reduced data, logs,
masks, wavelength, geometry) and only the record is lost. A load never sets the detector shift, so the
workspace has neither shift nor record, and NXstress writes the nominal chain with calibrated=False. Only
(c) leaves a trace, as one warning line in the log.
Evidence:
workspaces.py,_read_recorded_calibration:
if record.get("source", "none") == "none" or "calibration" not in record: return None.file_object.py: when the record cannot be built,{"source": "unknown", "error": message}.- The agent's run through the real method:
unknown+error -> None,json, no calibration key -> None,
AttributeError (bug) -> None. Only the last one warned.
G3 — How calibration errors are carried — valid; one question for the author, one open question
Comment (agents):
- Unknown errors are written as −1, which the calibration-file convention (
calibration_nexus.py, and the
project file'scodesattribute) defines as "not refined (or held)". So
a refined calibration whose errors were lost reads as "held". −2 means "refined but undetermined". - With several workspaces, the errors come from
wss[0]only. When the shifts agree but the errors differ,
the first workspace's errors win silently. The agent's run:same shift, errors 0.03 vs 9.0 -> 0.03. _shift_values(append) ignores the errors when comparing.- If only some
<name>_errorsfields are present,shiftErrorFromNexusreturnsNonewithout a warning,
and the next write turns all seven into −1.
Reviewer:
- Wherever the code "uses the first workspace", the fallback is useless. In general the right response to
inconsistent inputs is to warn, and mark the values as inconsistent; whether to refuse is decided case
by case, because refusing shuts down GUI options. - For example: differing errors for the same shift indicate a different calibration, a case that probably should be
refused.
Resolution: valid. #1132 takes the first input's errors, with no check and no warning, in two places:
_Instrument.init_group:shift_error = cls._applied_shift(wss[0])[1]. A multi-workspace write keeps the
first workspace's errors._Instrument.validateAppend: compares geometry and shift with what is on disk, but never reads the
on-disk errors (shiftErrorFromNexusis not called). An append whose errors differ is accepted, and the
entry keeps the first write's errors.
In PyRS core, append_hidra_project compares with _shift_values, which also ignores the errors: same shift,
different errors keeps the first file's errors, with no warning.
The errors come out of the same refinement as the values, so they are part of the calibration. Seven
bit-identical values with different errors are either two refinements or a sign that something went wrong
(values copied, a parameter held in one run and refined in the other, a hand-edited file). Neither can be
told apart from the data, so it is treated as a different calibration.
Suggestion, case by case:
- Both inputs carry errors, and they differ: refuse, exactly as for a differing shift (R2). NXstress
refuses in_entry_wide_geometryandvalidateAppend; a PyRS-core merge records the calibration as
CalibrationSource.UNKNOWN, as R2 does for differing shifts. G1's
content hash covers the values and the errors, so one key comparison detects it. - One input's errors are missing (lost on some path): see the open question below. Until it is answered,
the working rule is: do not refuse; warn, and keep the errors that are known. They are not "the first
input's" errors but the only ones there are. - A partial
_errorsset read back from NXstress: warn and mark the errors inconsistent, rather than
reading them as "no errors" and writing −1 on the next save. Not a refusal: the file must still load. - Question for the author, revisiting a recorded decision: #1132's ground truth records "−1 where none are
known" as a user decision, and it is the conventionread_calibration_nexusalready uses (#1098). So
this is not a bug. The reason to revisit it: G2's "unknown" and G3's "errors inconsistent" are new states,
and −1 ("not refined (or held)") would label a refined calibration as held in both. Should a calibrated
entry whose errors are unknown or inconsistent use −2 ("refined but undetermined"), or a distinct code?
OPEN QUESTION — is a calibration without errors a different calibration? The reviewer's view: it
probably should be. If so, values-without-errors and the same values-with-errors are refused like any
other differing calibration, and the content hash simply includes the "errors unknown" state. If not, two
records match on the values, and on the errors only when both carry them, which the hash comparison has to
special-case. The answer also decides how often a save is refused in practice: today, several paths lose
the errors (_applied_shiftreturns no errors whenever the workspace's shift does not match its record,
and a partial_errorsset reads back as none).
Not affected: the masks also come from wss[0], but _validate_masks_agree checks every input first
(pre-existing). instrumentFromNexus's local first(*names) is the first field name present, not the
first workspace; see G9 (1).
G4 — Tests for the recorded-calibration path — valid, important
Comment: every append test builds its workspace with make_minimal_HidraWorkspace(with_instrument=True),
which calls set_detector_shift. So no test reaches _applied_shift's recorded-only branch, which is the
normal case for a workspace loaded from a project file, through a multi-workspace write or an append. The
write-time refusal "input workspaces disagree on detector shift" has never been tested (that part predates
#1132). If _entry_wide_geometry reverted to get_detector_shift(), only the two single-workspace tests
below would fail; no multi-workspace write or append test would (checked by patching it: 2 failed, 118 passed, 2 xfailed).
Checked: the recorded-only branch is covered for a single workspace:
test_instrument.py::test_errors_are_the_recorded_calibrations (shift None, record set) and
test_errors_survive_a_read_back_and_rewrite. The gap is the multi-workspace write and the append, where the
shifts are compared.
Resolution: valid. Suggested unit tests, named by the agent:
test_differing_recorded_calibrations_are_refused(parametrized "other" / "none");test_shared_recorded_calibration_merges;test_append_of_recorded_calibration_only(parametrized "same" / "other").
These three stay valid whatever G1–G3 decide: R2 keeps the refusal of differing shifts.
Tests that G1–G3 will change. Under G1, every test whose workspace carries only a detector shift (the
make_minimal_HidraWorkspace(with_instrument=True) default) must also set the record: a trial patch of
_applied_shift to read only the record fails 8 NXstress unit tests (in test_instrument.py, test_append.py
and test_workspace_read.py). Two of them pin behaviour that is meant to change. Whoever implements G1 or G3
should expect to rewrite them, not treat their failure as a regression:
test_own_shift_wins_over_another_recordpins_applied_shift's preference for the workspace's shift over
the record. G1 removes that preference: NXstress reads only the record.test_errors_unknown_are_not_refinedpins −1 for lost errors. It depends on G3's question to the author
(−1 or −2) and on G3's open question.
Tests that come with G1–G3. Each change brings its own tests, written by the PR (or commit) that implements it, not
by this review:
- G1: reduction sets the record (
Nonefor nominal); the content key; a reload restores the record. - G2: each failure case records "unknown"; NXstress writes the "calibration unknown" marker; the bad-file and
PyRS-bug cases log differently. - G3: differing known errors are refused; missing errors as G3's open question decides (the working rule:
warn and keep the known ones); a partial_errorsset warns and is marked inconsistent.
Minor: test_arm_angles_and_length_are_the_runs has a dead if l2 is None else l2 branch. HB2B_3510 has
no L2 log, so the test could assert that directly.
Evidence:
grep -rn "disagree on" testsmatches onlytest_sample.py's stress-direction refusal.- The agent's run:
0.3 0.4 refused,0.3 None refused,0.3 0.3 accepted. The behaviour is correct
today; nothing pins it.
G5 — Factual errors in the documentation, and in a note written into files — valid, critical (docs)
Comment:
-
PowderPatternCalculatordoes not exist (workspaces.py__init__comment;ground_truths.md). The
class isReductionApp. -
ground_truths.mdsays the old chain was "the reverse ofDetectorModel.lab_positions". It was not:- the rotation sub-order (Rz, Ry, Rx) matched;
- 2θ₀ came first instead of last;
- the translations came after the rotations instead of x/y before them.
This was checked against
CALIBRATION_TRANSFORMATIONS: shift_x, shift_y, rotation_z, rotation_y,
rotation_x, arm_length, shift_z, two_theta_0, arm_rotation. -
detector_transformationsnow writes thearm_rotationnote "-(DAS arm 2theta), per sub-run" into
calibration files too, where the value is 0 by rule. The old wording, "set per sub-run to …", was true for
both kinds of file. Suggestion: one note per caller.
Resolution: valid. Ground truths are what later work relies on, so the first two should be fixed in this PR.
The note is smaller, but it is written into data files: every calibration file saved with #1132 carries a note
describing a value it does not hold (the reader refuses a non-zero arm_rotation there). A fix to the code
does not reach files already written, so it should be fixed before #1132 merges.
G6 — Comments left stale by the change — valid, suggestion
_instrument.pystill sayswavelengthis the only field an append grows: theappendableDatasets
docstring ("just the wavelength"), twovalidateAppendcomments, and theinit_groupappend branch ("the
one per-scan-point field"). #1132 makesarm_rotationgrow too. #1132 should fix these, since its change
made them stale; the same lines are on the phase-3 branch, so R1's follow-up 2 becomes a check after the merge._entry_wide_geometry's docstring does not mention the L2 geometry or the applied shift, and promises a
"calibration state" it does not return. Once G3 is done, the corrected docstring should also name the
errors among what the inputs must agree on._applied_shift's docstring says a read-back shift has "no known errors"; the code gives it the recorded
errors. G1 removes this fallback, so the docstring is worth fixing only if G1 is postponed.- The "written before #1099" hint in
validateAppend. It is added only when the entry on disk has no
arm_rotation, i.e. was written before #1099, not to every mismatch. But even then the mismatch may be a
genuinely different calibration, so the hint should not name the entry's age as the cause. Suggested
wording: "may be why; if so, write a new entry". _shift_valuesand the append comment do not say that the errors are ignored: covered by G3, which
makes the errors part of the comparison.- Smaller points:
transformation_chainstill calls NXstress output future work: "(and, later, NXstress output)".detector_transformationschanges the attributes of the field it is given, undocumented._written_order,test_the_rotation_links_are_written_in_xyz_orderandTestDetectorRotationOrder's
"leaves both of them green" describe the old write order.- Explain why
appendableDatasetschecksdatasets and.
G7 — Project rules — valid, important
Type hints and docstrings are CLAUDE.md rules. The others are, for now, only in CLAUDE.local.md, and each
is marked "(see Recommended coding rules, above)".
-
Keyword-only arguments (see Recommended coding rules, above):
detector_transformations(shifts, shifts_error, arm_length, arm_rotation=None)has four arguments, one with a default, and both callers (calibration_nexus.py,
_Instrument.init_group) pass them by position. The first two are bothOptional[DENEXDetectorShift], so
swapping the shift and its errors raises nothing, in Python or in mypy. Also,
shift if is_calibrated else Noneis justshift:is_calibratedisshift is not None. -
Type hints and Google docstrings (
CLAUDE.md), on the new methods:- no annotation at all on
_shift_values,_read_recorded_calibrationandget_recorded_calibration. mypy
skips the body of an unannotated function (its ownannotation-uncheckednote), so these are not checked; set_recorded_calibration(-> None) andshiftErrorFromNexus(-> DENEXDetectorShift | None) are
partly annotated: their bodies are checked, but their arguments areAny.
So the
(shift, shift_error)contract NXstress depends on, read throughget_recorded_calibration, is
never checked. - no annotation at all on
-
set_recorded_calibration(shift, shift_error=None)("count the fillers", from theNonerule; see
Recommended coding rules, above): all five callers (one in production, the NXstress read-back, and four tests) pass the errors argument, so the default only lets a future caller drop them unnoticed;
andset_recorded_calibration(None, err)silently discardserr. -
A record type is the vehicle for G1–G3. The agents offered a small frozen
AppliedCalibration(shift, shift_error)in place of the bare tuple as the author's option. After G1–G3 it is no longer optional: the
record must carry its source as aCalibrationSourceliteral (R2), includingUNKNOWNwith its reason (G2), a content key (G1), and an error state
(known, lost, inconsistent; G3), whileNonemeans only "nominal detector". A bare(shift, error)tuple
cannot express that. A typed record type also settles the two items above. The tuple fixes (type hints, no
default) apply only if G1–G3 are postponed. -
Function-local imports with no justification (see Recommended coding rules, above): #1132 adds five
intests/unit/pyrs/core/test_workspaces.py, in two test functions and the helper_calibrated_instrument.
Theh5pyandHidraProjectFileModeimports in an earlier test predate #1132. -
A test imports another test module's private helper (see Recommended coding rules, above):
test_nxstress_calibration.py
imports_chain_matrixfromtest_instrument.py. The rule's test exception covers only a test importing
from the module it tests. Move it totests/util/.
G8 — Simplifications — one important; the rest suggestions
All behaviour-preserving. G1–G3 decide which are still worth asking for.
Worth doing whatever G1–G3 decide:
- Important:
shiftErrorFromNexustypes the seven names out again. The writer,
detector_transformations, builds the<name>_errorsfields fromCALIBRATION_TRANSFORMATIONS; the reader
has its own tuple. A rename in the table makes every read returnNonesilently, which reads as "an entry
written before #1099", i.e. the lost-errors case G3 says must warn. Take the names from the table, as
read_calibration_nexusdoes, and buildDENEXDetectorShiftby keyword: the table is in chain order, not
constructor order, so positional*valueswould misassignshift_zand all three rotations. validateAppend's "written before #1099" hint is built inline in the message, inside the loop.
Compute it before the loop; do it together with G6's rewording of that hint._effective_geometry. The L2 set comprehension wraps a generator; build it in two steps. The bare
FalseinDENEXDetectorGeometry(rows, columns, pixel_x, pixel_y, l2.pop(), False)is thecalibrated
flag of R3, which the class discards today. Under the suggested DD-35 (keep the flag, refuse a second
shift) it would start to matter, and would mark this geometry uncalibrated. Pass it by keyword,
calibrated=False, so it is visible, and whoever implements DD-35 should check this call._load_recorded_calibrationis one assignment. Keeping it to mirror_load_wave_lengthis fair; if
kept, its docstring belongs on_read_recorded_calibration.
Overtaken by G1–G3; only if those are postponed:
- The inner
ifinappend_hidra_projectis always true. G1 and G3 rewrite that block. - Two "same calibration" keys,
_shift_valuesand_shift_key(detector_model.from_shiftalready
gives the vector). G1's content key replaces both. _applied_shiftrebuilds a tuple it already has. G1 removes the fallback, and with it the method.
Covered elsewhere: keyword-only arguments for detector_transformations in G7; the
appendableDatasets docstring and its datasets and coupling in G6.
G9 — Pre-existing or minor
Reviewer: fields missing from a file raise two distinct concerns. (1) The NXstress backend should not read missing fields as zero.
(2) In PyRS core (e.g. the HidraProjectFile reader), the question is whether we can, or should, change
existing behaviour much.
(1) NXstress: missing fields are read as 0.0 — valid, important. Pre-existing; #1132 kept it and
extended it to the new names. In _Instrument.instrumentFromNexus, the local first(*names) returns 0.0
when none of its names is in the file:
- no
arm_length(or pre-#1099distance): 0.0 reachesDENEXDetectorGeometry, which refuses it
(ValueError: "Arm length" value=0.0 ... below minimum), so the read fails with a message that does not name
the missing field; calibrated=Trueand a shift field missing: that parameter becomes 0.0, an invented calibration value.
Nothing is logged. NXstress always writes every field, so a missing one means a truncated, damaged or foreign
file. Raising would refuse the load, which the warn-and-mark rule (G3) avoids where it can. Suggestion:
- a missing calibration field: warn, and record the calibration as unknown (G2's state);
- a missing arm length: warn, and store NaN, as #1132 already does for a missing arm angle (below), instead
of today's refused read. A viewer reading strains does not need it, any later computation with it fails
visibly, and the constructor accepts NaN.
If #1132 does not fix it, record it as DD-36. DD-35 (R3) and DD-36 collide with neither branch: phase 3
uses up to DD-33, #1132 up to DD-34.
(2) PyRS core: its own zero-default, and existing behaviour stays — no change proposed.
calibration_file_io.check_calibration_dictionary, whichcalibration_from_dictcalls after its wavelength
check, sets a missing
Shift_*/Rot_*/TTH_0to 0 with error −1, and a missing error to −1 (its docstring: "Missing
parameters are set to 0 with an error of -1").calibration_from_dict({'Lambda': 1.5, 'Status': 3, 'Shift_x': 0.01})returns a shift with every other parameter 0.0 and every error −1, without a warning.calibration_from_dictrefuses a missing or unusableLambda(ValueError), conflictingTTH_0and
two_theta_0(ValueError) or a missingStatus(RuntimeError), but no missing shift parameter.HidraProjectFile.read_instrument_geometryreadsdetector_group["L2"]directly: a missing L2 is a
KeyError.
This zero-default is long-standing core behaviour: changing it would change results for every existing
calibration file read through it, so it is not asked of #1132. At most it is worth a deferred defect of its
own, if the PR's author agrees it is one. The proposals in this review
that touch core (G1–G3, R2) change code #1132 itself adds (_read_recorded_calibration's handling of those
exceptions: G2's separate catch blocks and "unknown"; append_hidra_project's calibration merge), plus
pre-existing core code: one new step in ReductionApp.reduce_data, setting the record (G1); the content key in
the project file's record (G1); and CalibrationSource in HidraSetup and HidraProjectFile, including how a
file with no record loads (R2). None of these changes a reduced value. Each is still a production change needing the PR author's approval.
A missing 2theta log is written as NaN, silently — suggestion. Caused by #1132. The NaN is
honest and pinned by test_missing_arm_angle_is_nan, but nothing is logged, and _concatenated_arm_rotation's
except RuntimeError would also swallow any other RuntimeError from get_detector_2theta: the same
problem as G2's broad except. Suggested Fix: check for the log by name, warn once per workspace, and catch
nothing.
L2 values are compared for exact equality — no action. A difference refuses the write: a refusal
where the detector really is placed differently, like a differing shift, so consistent with G3's case-by-case
rule. No float noise has been seen; revisit only if it is.
R5 — Grounding the detector chain: the sample chain is cited, the detector chain is not
Reviewer: the sample and detector chains are analogous, and both bear on calibration. The sample chain's
rotation order was reconstructed by a probe from a cited reference; the detector chain should be grounded the
same way, in a citation, rather than in "what the code's authors specified as correct".
What the two chains share:
- Both are
NXtransformationschains placing something in the lab frame:SAMPLE_DESCRIPTION/transformations
andDETECTOR/transformations. - Both can fail in the same ways: axis directions and signs, composition order, and the entry point.
Implementing the 04 nxstress-internal-cleanup subspec for the NXstress hookup found the detector chain's
entry point wrong (1 of 8 links reachable; decision 26 in that plan's decisions log); the sample chain
was written to avoid the same defect. - Both mix constant parameters with per-scan-point values. The sample chain has a constant
frame_offsetand
per-pointvx/vy/vz,omega/chi/phi. The detector chain has the calibration (shifts, rotations, 2θ₀) and a
per-pointarm_rotation. - Both feed calibration-dependent results. The detector chain is the calibration; the sample chain fixes the
sample side of the scattering geometry, on which pole figures depend.
How each is grounded:
| Sample chain | Detector chain | |
|---|---|---|
| Referent | PoleFigureCalculator.rotate_project_q, which implements Bob He, Two-Dimensional X-ray Diffraction, ch. 8.3 (cited in its docstring and in _sample.py) |
DetectorModel.lab_positions / detector_model.rotation_matrix: code, no citation |
| How it was established | We probed the formula, driven as a black box, for its matrix; of 2880 candidate compositions exactly one survives, M0 @ R_omega(0,-1,0) @ R_chi(1,0,0) @ R_phi(0,0,-1), worst error 5.8e-14 |
Decision 26: only the rotation sub-order (Rx @ Ry @ Rz) was compared with reduce_hb2b_pyrs.generate_rotation_matrix (since removed, #1011; replaced by detector_model.rotation_matrix). #1132: the whole chain against lab_positions, to 1e-12 m |
| Pinned by | test_sample.py::TestSampleTransformationChain::test_the_rotations_compose_in_write_order, against rotate_project_q itself |
test_instrument.py, against lab_positions |
| Status | Landed with the 04 internal-cleanup work (i.e. 'phase 2'); #1132 does not touch it | #1132 |
What this shows:
- A check against code is only as good as the code, and only as wide as the check. Decision 26 concluded
"the written order was already correct" from the rotation sub-order alone. #1132 resolved the 2θ₀ axis
(about X, already flagged as open in the old writer) and found the rest of the old chain wrong: 2θ₀ applied
first, the translations after the rotations. #1132's own test proves
that NXstress places pixels where reduction does, not that reduction is right. - Nothing checks that the two chains share one lab frame. The detector side states +Z along the beam,
+Y up (calibration_nexus.py). The sample side needs a constant 180°frame_offsetabout +x to map ch. 8.3's
output frame onto PyRS's, and the 04 work left open whether that offset is physical or an artefact of the
convention. Each chain is tested alone, so a sign disagreement between them passes every test.
Suggestion:
- Ground the detector chain in an external referent, the way the sample chain is, with a probe and a test
against that referent. Candidates, none yet checked:- He's book, which may also treat the geometry of a 2D detector (a lead; the chapter is not identified);
- Mantid's HB2B instrument definition, which reduction through Mantid uses.
- Add one test that composes both chains in the same lab frame, e.g. the scattering vector of a pixel
computed from the written sample and detector chains, againstrotate_project_q's convention. - Neither change is a defect in #1132. Both are follow-up work; the timing is the PR author's call.
- Ours, after this review (not asked of #1132): correct decision 26's conclusion in our plan records for the
04 work, pointing here and at #1132's ground truth.
Evidence:
grep -rn "Bob He" pyrs→polefigurecalculator.py(rotate_project_qdocstring) and_sample.pyonly.detector_model.pyandreduce_hb2b_pyrs.py: no citation for the rotation convention.git diff 9fd090e2...19dd2525 --stat: neither_sample.pynortest_sample.pyis changed.
…-compat, missing fields refused Addresses parts of the #1132 review (G5, G6, G9) with user-approved changes: - Calibration NeXus file: the transformation chain ends at two_theta_0 and holds no arm_rotation. The file stores the calibration parameters only; PyRS builds the instrument from them and each sub-run's arm angle. The reader checks shift_x..two_theta_0 and skips an arm_rotation entry. detector_transformations takes arm_rotation as a required keyword; the arm_rotation note is written only by NXstress, where it is true. - No backward compatibility for NXstress or calibration NeXus files: removed the pre-#1099 old-name fallbacks, the before_1099 append hint and the arm_rotation presence guards. An append needs both per-scan-point fields (_Instrument._APPENDED) and is refused naming a missing one. - instrumentFromNexus refuses a missing field (pixel layout, calibrated flag, arm_length, calibration values, wavelength) with a RuntimeError naming it, instead of reading 0.0 or defaulting to uncalibrated. - Docs (G5/G6): ReductionApp, not PowderPatternCalculator; the old chain's real differences from lab_positions; stale comments on what an append grows, _entry_wide_geometry, _applied_shift and the rotation-order tests. No reduced value changes. Follow-ups: #1140, #1141 (calibration hash, nominal calibration), #1142 (errors required in calibration files). Refs #1099, #1132 Assisted-by: Claude Code
… errors, test helpers - detector_transformations(shifts, *, shifts_error, arm_length, arm_rotation): the shift and its errors (both Optional[DENEXDetectorShift]) can no longer be swapped by position; both callers pass them by name. `shift if is_calibrated else None` is just `shift`. - HidraWorkspace.set_recorded_calibration: shift_error is required; every caller passed it, and the default only let one drop it unnoticed. - Tests: the #1132 function-local imports in test_workspaces.py move to the top; chain_matrix and rodrigues move to tests/util/transformation_helpers.py as public helpers, so the integration test no longer imports a private name from another test module. Type hints on the (shift, errors) tuple are left to #1141, whose record type replaces it and which merges before this PR. No computed value changes. Refs #1099, #1132 Assisted-by: Claude Code
…ing errors refused - shiftErrorFromNexus takes the parameter names from CALIBRATION_TRANSFORMATIONS (the writer's table) instead of its own copy, and builds the shift by keyword through the new public calibration_nexus.shift_from_parameters (shared with the calibration file reader). A missing <name>_errors is refused by name: NXstress always writes all of them, so one missing is a failed write or a corrupt file. - _effective_geometry: L2 values gathered in two steps; the calibrated flag passed by keyword (calibrated=False), for DD-35 (#1143). - append_hidra_project: drop an inner `if` that was always true. - _applied_shift: return the recorded tuple instead of rebuilding it. - Ground truths: the "-1 where no errors are known" decision is superseded (-1 default, -2 unknown), to be implemented by #1141. No computed value changes; a corrupt NXstress file is refused. Blocked by #1141, #1142, #1143 (must merge first). Refs #1099, #1132 Assisted-by: Claude Code
…corded-calibration tests - NXstress refuses a workspace without a 2theta log (RuntimeError naming the workspace): without the arm angle the detector cannot be placed (user decision, G9). It used to write NaN, and its `except RuntimeError` could hide other errors; the log is now checked by name and nothing is caught. - make_minimal_HidraWorkspace sets a 2theta log by default, as real data has (with_arm_angle=False to omit it). - G4: TestRecordedCalibrationAcrossWorkspaces covers workspaces that carry only a recorded calibration (as loaded from a project file): differing records (another calibration, or none) are refused in a multi-workspace write; a shared one merges with its errors; an append with the same record grows the entry, with another is refused. Four of the five fail if _applied_shift ignores the recorded calibration. - test_arm_angles_and_length_are_the_runs: dead L2 branch removed; HB2B_3510 has no L2 log, which the test now asserts. - Ground truths: arm angle required; calibration defaults (0, error -1) and L2 as part of the calibration hash (#1141). No computed value changes for data with a 2theta log. Refs #1099, #1132 Assisted-by: Claude Code
…#1132 review R5) Assisted-by: Claude Code
…ilot mirror Adds five rules after "Code Quality Standards", proposed in the review of #1132 and adopted by the maintainer: - `None` must name a value, not a gap - Keyword-only arguments - Import placement - Private names do not cross module boundaries - Named states are literals, not free text Adapted from the proposal: rule 5 has no UNKNOWN member, and a stored string that is not a member is rejected, not mapped to a fallback (the maintainer's decision for calibrations, #1141). Rule 4's NXstress file list names only files on `next`. A review pass corrected factual claims (existing functions already cross the keyword-only threshold; three deferred imports in _peaks.py; one source default, in HidraSetup), "Three things", and the examples' return type hints. Adds .github/copilot-instructions.md, which CLAUDE.md has always named as its mirror but which did not exist: the same text, with links relative to .github/. Refs #1132 Assisted-by: Claude Code
…tation (review) Assisted-by: Claude Code
|
Thanks for the thorough review. Below, each item is answered in the review's order (R1 → R5, with G1–G9 under R4), then the recommended coding rules. Each production change was approved individually by the maintainer. Outcome: what fits #1132 is done on this branch, R1 — Merge orderDecision: #1140, #1141, #1142 and #1143 merge first, then #1132, then NXstress phase 3. #1099 is marked blocked by all four. This replaces the proposal that #1132 go ahead of phase 3 on its own. The calibration work this review surfaced has to land first. R2 — One NXstress entry holds one calibrationDecision: keep the refusal, and never record an "unknown" calibration.
R3 — Can a detector shift be applied more than once?Decision: fix it before this PR, rather than deferring it. Your DD-35 is #1143, the discarded R4 — General review
R5 — Grounding the detector chainDecision: the detector chain is a self-consistent choice. PyRS defines it in Recommended coding rulesAll five are adopted in #1144 (merged), together with the Also found: DD-36. A refused NXstress write can leave a partial file. GUI saves are protected; direct use of Coordination: #1140 reverses decision 18 of your plan (one wavelength per entry) and overlaps phase 3, so let's agree on it there. 🤖 Generated with Claude Code |
CLAUDE.md: adopt five coding rules from the #1132 review; add the Copilot mirror
- _Instrument._required: type hints and Google docstring. - test_chain_with_wrong_link_is_refused: a transformation's depends_on is checked (nothing failed if that comparison were dropped). - make_minimal_HidraWorkspace: the default 2theta log is derived from the sub-run numbers, so workspaces over different sub-runs differ and an ordering bug in a multi-workspace write or append shows. - TestRecordedCalibrationAcrossWorkspaces: assert the arm angles' values, not only the array length. - test_append_without_arm_angle_leaves_file_unchanged; a missing DETECTOR/transformations group is refused by name; test_instrumentFromNexus_standalone uses Arrange/Act/Assert. Defects recorded, not fixed: - DD-36: a refused NXstress write can leave a partial file (GUI saves are protected; direct NXstress use is not). Refs #1099, #1132 Assisted-by: Claude Code
…-chain # Conflicts: # docs/deferred_defects.md # docs/ground_truths.md
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## next #1132 +/- ##
==========================================
+ Coverage 87.12% 87.18% +0.06%
==========================================
Files 106 106
Lines 16655 16702 +47
==========================================
+ Hits 14510 14562 +52
+ Misses 2145 2140 -5
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
@ekapadi I've restructured my reply to your review so it goes through R1 → R5 in order, with G1–G9 under R4: #1132 (comment) Since then the branch has merged the current |
What
NXstress now writes the detector chain the calibration file uses, so external NeXus tools place the pixels where PyRS reduction does (#1099, the last phase of #1054).
calibration_nexus.detector_transformationswrites it for both files: shift_x, shift_y, rotation_z, rotation_y, rotation_x, arm_length, shift_z, two_theta_0 (about Y), arm_rotation. The detector'sdepends_onistransformations/shift_x.arm_rotationholds one value per scan point, −(the2thetalog). It grows on append and is NaN without a2thetalog.L2log when there is one, else the instrument's. An entry whose L2 differs between scan points is refused.<name>_errorsvalue; −1 where the error is unknown. Errors survive reading an entry back and writing it again.get_recorded_calibration()), and NXstress writes that.get_detector_shift(), so re-reducing a project file without a calibration file still uses the uncalibrated geometry, as before.instrumentFromNexusreads the new names first, then the old ones. A refused append to an entry written before NeXus calibration phase 4: NXstress output uses the calibration file's transformation chain #1099 says so in its message.Tests
test_nxstress_calibration.py(new): reduces HB2B_3510 with the ring reference calibration and checks that the written chain places the real pixels wherelab_positionsdoes, with that calibration's values and errors.pixi run mypy pyrs scripts tests.Reviews
Deferred
DD-34: a project file that reduction writes to a new path has no instrument geometry, so NXstress can't be written from it. This affects Manual Reduction's output. The problem predates this PR and is recorded in
docs/deferred_defects.md.Refs #1099, #1054
🤖 Generated with Claude Code